package com.estar.assistsurvy.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import com.estar.app.appsrvyspds.domain.ReturnSubVideoSrvyVO;
import com.estar.assistsurvey.entity.ImageVO;
import com.estar.assistsurvy.R;
import com.estar.assistsurvy.adapter.BaseRVAdapter;
import com.estar.assistsurvy.adapter.BaseViewHolder;
import com.estar.assistsurvy.constant.Constants;
import com.estar.assistsurvy.entity.CaptureInfo;
import com.estar.assistsurvy.entity.MettingMessageVO;
import com.estar.assistsurvy.entity.RequestCapture;
import com.estar.assistsurvy.entity.RequestData;
import com.estar.assistsurvy.entity.RequestHead;
import com.estar.assistsurvy.entity.ResponseCapture;
import com.estar.assistsurvy.service.ImageService;
import com.estar.assistsurvy.thread.CaptureThread;
import com.estar.assistsurvy.utils.ExitUtils;
import com.estar.assistsurvy.utils.FileUtil;
import com.estar.assistsurvy.utils.LogUtil;
import com.estar.assistsurvy.utils.TimeUtils;
import com.nineoldandroids.animation.ObjectAnimator;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.SensorManager;
import android.location.Address;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import info.emm.meeting.MeetingSession;
import info.emm.meeting.MeetingUser;
import info.emm.utils.NotificationCenter;
import info.emm.utils.NotificationCenter.NotificationCenterDelegate;

public class VideoActivity extends BaseActivity implements
NotificationCenterDelegate,OnClickListener{

	public static final int WEIYI_VIDEO_OUT_SLOW = 1; // 视频发送速度慢
	public static final int WEIYI_VIDEO_OUT_DISCONNECT = 2; // 视频发送连接断开重连
	public static final int WEIYI_VIDEO_IN_SLOW = 3; // 视频接收速度慢
	public static final int WEIYI_VIDEO_IN_DISCONNECT = 4; // 视频接收连接断开重连
	public static final int WEIYI_AUDIO_DISCONNECT = 10; // 音频连接断开重连
	public static final int WEIYI_AUDIO_DISABLED = 11; // 未能取得打开麦克风权限

	private boolean hasfront;//是否有前置像头
	private boolean usefront;//是否是前置摄像头
	private boolean isVideo;//是否打开视频
	private boolean sparkBoolean;//是否打开语音
	private boolean loundSpeak;//是否外放

	private int myPid;//
	//    @BindView(R.id.surfaceView)
	private SurfaceView surfaceView;
	//    @BindView(R.id.msgRecyclerView)
	private RecyclerView msgRecyclerView;
	//    @BindView(R.id.msgControlBtn)
	private ImageButton msgControlBtn;
	//    @BindView(R.id.msgLayout)
	private LinearLayout msgLayout;
	//    @BindView(R.id.rightLayout)
	private RelativeLayout rightLayout,returnBack;
	private ImageButton photoGraph,photoPreview;
	private TextView survyAddress;
	private Button sendMsg;
	private boolean isOpenMsgLayout = true;//是否打开聊天界面
	private String address;
	private String msgId="";
	private String userName;
	private String mettingId;
	private ReturnSubVideoSrvyVO returnSubVideoSrvyVO;

	private List<MettingMessageVO> messageList = new ArrayList<MettingMessageVO>();//消息列表
	private Camera mCamera;
	private CameraOrientaitonListener orientaitonListener;
	private int mLayoutOrientation;
	private int mDisplayOrientation;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		Window window = getWindow();//得到窗口
		requestWindowFeature(Window.FEATURE_NO_TITLE);//没有标题
		window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
				WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏
		window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//设置高亮
		setContentView(R.layout.activity_video);
		initView();
		init();

		//子线程请求抓拍命令，每三秒一次
		runnable.run();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		if (isVideo) {
			MeetingSession.getInstance().resumeLocalVideo();
		}
		new MyThread().start();

	}
	
	class MyThread extends Thread{
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				MyThread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			JSONObject params = new JSONObject();
			try {
				params.put("senderID", myPid);
				params.put("toID", 0);
				params.put("name", userName);

			} catch (JSONException e) {
				showShortToast("发送消息 错误");
				e.printStackTrace();
			}
			MeetingSession.getInstance().sendTextMessage(0,"定损员，您好!\n我在"+address , params);

		}
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();

		if (isVideo) {
			MeetingSession.getInstance().pauseLocalVideo();
		}
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		handler.removeCallbacks(runnable);
	}

	private void init(){
		orientaitonListener = new CameraOrientaitonListener(this);
		returnSubVideoSrvyVO = (ReturnSubVideoSrvyVO) getIntent().getSerializableExtra("returnSubVideoSrvyVO");
		mettingId = returnSubVideoSrvyVO.getMeetId();
		userName = returnSubVideoSrvyVO.getSryNme();

		initVideo();
		
//		MettingMessageVO mettingMessageVO = new MettingMessageVO();
//		mettingMessageVO.setType(MettingMessageVO.TYPE.SELF);
//		mettingMessageVO.setMessage("定损员，您好!\n我在"+address);
//		messageList.add(mettingMessageVO);
		setMsgAdapter();
	}

	private void initVideo() {
		usefront = hasfront = MeetingSession.getInstance().Init(
				getApplicationContext(), "demo", "", true);
		addVideoObserver();

		int uid = (int) (Math.random() * 100000);
		MeetingSession.getInstance().switchCamera(usefront);
		MeetingSession.getInstance().setCameraQuality(true);
		MeetingSession.getInstance().setLoudSpeaker(true);
		MeetingSession.getInstance().enterMeeting(Constants.VIDEO_IP,
				Constants.VIDEO_PORT, userName, mettingId,
				uid, false, 0);
		
	}


	public void addVideoObserver() {
		NotificationCenter.getInstance().addObserver(this,
				MeetingSession.NET_CONNECT_ING);
		NotificationCenter.getInstance().addObserver(this,
				MeetingSession.NET_CONNECT_SUCCESS);
		NotificationCenter.getInstance().addObserver(this,
				MeetingSession.NET_CONNECT_FAILED);
		NotificationCenter.getInstance().addObserver(this,
				MeetingSession.NET_CONNECT_BREAK);
		NotificationCenter.getInstance().addObserver(this,
				MeetingSession.NET_CONNECT_ENABLE_PRESENCE);
		NotificationCenter.getInstance().addObserver(this,
				MeetingSession.NET_CONNECT_USER_IN);
		NotificationCenter.getInstance().addObserver(this,
				MeetingSession.NET_CONNECT_USER_OUT);
		NotificationCenter.getInstance().addObserver(this,
				MeetingSession.NET_CONNECT_WARNING);
		NotificationCenter.getInstance().addObserver(this,
				MeetingSession.UI_NOTIFY_CHAT_RECEIVE_TEXT);
		NotificationCenter.getInstance().addObserver(this,
				MeetingSession.UI_NOTIFY_USER_VEDIO_CHANGE);
		NotificationCenter.getInstance().addObserver(this,
				MeetingSession.VIDEO_NOTIFY_CAMERA_DID_OPEN);
		NotificationCenter.getInstance().addObserver(this,
				MeetingSession.VIDEO_NOTIFY_CAMERA_WILL_CLOSE);
	}

	/**
	 * 初始化聊天列表
	 */
	public void setMsgAdapter() {
		msgRecyclerView.setLayoutManager(new LinearLayoutManager(this));
		//        msgRecyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayout.HORIZONTAL,DisplayUtil.dip2px(this,5), Color.TRANSPARENT));
		msgRecyclerView.setAdapter(new BaseRVAdapter<MettingMessageVO>(messageList, R.layout.item_message, this) {
			@Override
			public void dataBindView(BaseViewHolder holder, MettingMessageVO o) {
				if (o.getType() == MettingMessageVO.TYPE.SELF) {
					holder.getTextView(R.id.rightMsgTv).setVisibility(View.VISIBLE);
					holder.getTextView(R.id.leftMsgTv).setVisibility(View.GONE);
					holder.getTextView(R.id.rightMsgTv).setText(o.getMessage());
				} else {
					holder.getTextView(R.id.rightMsgTv).setVisibility(View.GONE);
					holder.getTextView(R.id.leftMsgTv).setVisibility(View.VISIBLE);
					holder.getTextView(R.id.leftMsgTv).setText(o.getMessage());
				}

			}


		});

	}

	private void initView(){

		SharedPreferences share=getSharedPreferences("location", Context.MODE_PRIVATE);
		address=share.getString("adress", "");
		if(address.equals("")){
			address=share.getString("Poi", "");
		}
		surfaceView=find(R.id.surfaceView);
		msgRecyclerView=find(R.id.msgRecyclerView);
		msgControlBtn=find(R.id.msgControlBtn);
		msgControlBtn.setOnClickListener(this);
		msgLayout=find(R.id.msgLayout);
		rightLayout=find(R.id.rightLayout);
		photoGraph=find(R.id.photoGraph);
		photoGraph.setOnClickListener(this);
		photoPreview=find(R.id.photoPreview);
		photoPreview.setOnClickListener(this);
		sendMsg=find(R.id.sendMsg);
		sendMsg.setOnClickListener(this);
		survyAddress=find(R.id.survyAddress);
		survyAddress.setText(address);
		returnBack=find(R.id.returnBack);
		returnBack.setOnClickListener(this);
	}

	public class CameraOrientaitonListener extends OrientationEventListener {

		private int mCurrentNormalizedOrientation;
		private int mRememberedNormalOrientation;

		public CameraOrientaitonListener(Context context) {
			super(context, SensorManager.SENSOR_DELAY_GAME);
		}

		@Override
		public void onOrientationChanged(int orientation) {
			if (orientation != ORIENTATION_UNKNOWN) {
				mCurrentNormalizedOrientation = normalize(orientation);
			}
		}

		private int normalize(int degrees) {
			if (degrees > 315 || degrees <= 45) {
				return 0;
			}

			if (degrees > 45 && degrees <= 135) {
				return 90;
			}

			if (degrees > 135 && degrees <= 225) {
				return 180;
			}

			if (degrees > 225 && degrees <= 315) {
				return 270;
			}

			throw new RuntimeException(
					"The physics as we know them are no more. Watch out for anomalies.");
		}

		public void rememberOrientation() {
			LogUtil.f("orientation", "mCurrentNormalizedOrientation =="
					+ mCurrentNormalizedOrientation);

			mRememberedNormalOrientation = mCurrentNormalizedOrientation;
		}

		public int getRememberedNormalOrientation() {
			return mRememberedNormalOrientation;
		}
	}

	@Override
	public void didReceivedNotification(int id, Object... args) {
		LogUtil.f("didReceivedNotification", "手机端接收到的指令:" + Arrays.toString(args));
		switch (id) {
		case MeetingSession.NET_CONNECT_ING: {
			LogUtil.i("video", "video正在连接");
			showShortToast("视频连接中…");
		}
		break;
		case MeetingSession.NET_CONNECT_SUCCESS: {
			showShortToast("连接成功");
			sendMsg();
		}
		break;
		case MeetingSession.NET_CONNECT_FAILED:
		case MeetingSession.NET_CONNECT_BREAK: {
			showShortToast("连接中断");
		}
		break;
		case MeetingSession.NET_CONNECT_ENABLE_PRESENCE: {
//			showShortToast("连接成功");
			isVideo = true;
			MeetingSession.getInstance().StartSpeaking();

			myPid = (Integer) args[0];

			this.playVideo();
			// 开始录制自己的视频
			// 开始录制：
			startRecording();
			//	                insertUserInfo(
			//	                        MeetingSession.getInstance().getUserMgr().getSelfUser()
			//	                                .getName(), MeetingSession.getInstance()
			//	                                .getUserMgr().getSelfUser().getPeerID(), false,
			//	                        false);


		}
		break;
		case MeetingSession.NET_CONNECT_USER_IN: {
			// 用户进入会议（p1 int 用户peerID）（p2 boolean 是否比你先进入）
			int peerID = (Integer) args[0];
			boolean isEarlier = (Boolean) args[1];
			if (isEarlier)
				return;

			MeetingUser mu = MeetingSession.getInstance().getUserMgr()
					.getUser(peerID);
			if (mu == null)
				return;

			// 用户进入会议（p1 int 用户peerID）（p2 boolean 是否比你先进入）
			// MeetingUser mu = MeetingUserMgr.getInstance().getUser(
			// (Integer) arg1[0]);
			if (!(Boolean) args[1]) {
				// 比例先来的用户不用提示，只提示比你后进的用户
				if (mu != null) {
					showShortToast(mu.getName() + "进入了群组");
					sendMsg();
				}
			}

		}
		break;
		case MeetingSession.NET_CONNECT_USER_OUT: {
			// 用户离开会议（p1 int 用户peerID）（p2 String 用户名）
			int peerID = (Integer) args[0];
			String name = (String) args[1];

		}
		break;
		case MeetingSession.NET_CONNECT_WARNING: {

			String warningString = null;
			int warning = (Integer) args[0];
			if (warning == WEIYI_VIDEO_OUT_SLOW)
				warningString = "视频发送速度慢";
			else if (warning == WEIYI_VIDEO_OUT_DISCONNECT)
				warningString = "视频发送连接断开重连";
			else if (warning == WEIYI_VIDEO_IN_SLOW)
				warningString = "视频接收速度慢";
			else if (warning == WEIYI_VIDEO_IN_DISCONNECT)
				warningString = "视频接收连接断开重连";
			else if (warning == WEIYI_AUDIO_DISCONNECT)
				warningString = "音频连接断开重连";
			else if (warning == WEIYI_AUDIO_DISABLED) {
				warningString = "未能取得打开麦克风权限";

				new AlertDialog.Builder(this).setTitle("提示").setMessage("打开麦克风失败,请检查软件是否具有录音权限？有,请重启手机;没有,请开通权限").setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						exit();
					}
				}).show();
			} else
				warningString = "未知警告";

		}
		break;
		case MeetingSession.UI_NOTIFY_CHAT_RECEIVE_TEXT: {

			String nameText;
			if (args.length != 5)
				return;

			int fromID = (Integer) args[0];
			String text = (String) args[1];
			String name = (String) args[2];
			int msgType = (Integer) args[3];
			MettingMessageVO mettingMessageVO = new MettingMessageVO();
			mettingMessageVO.setType(MettingMessageVO.TYPE.OTHER);
			mettingMessageVO.setMessage(text);
			mettingMessageVO.setUserName(name);
			messageList.add(mettingMessageVO);
			msgRecyclerView.getAdapter().notifyDataSetChanged();
			LogUtil.i("111", "手机端接收的指令" + text);
			if ("@!$5D7B9ADCBE1C629EC722529DD12E5129".equals((String) args[1])) {
				exitMeeting(1, "后端人员视频暂存");
				break;
			}
		}
		break;

		case MeetingSession.UI_NOTIFY_USER_VEDIO_CHANGE: {
			int peerID = (Integer) args[0];
			MeetingUser mu = MeetingSession.getInstance().getUserMgr()
					.getUser(peerID);

			if (mu == null)
				return;

		}
		break;

		case MeetingSession.NET_CONNECT_USER_INLIST_COMPLETE: {

		}
		break;
		case MeetingSession.NET_CONNECT_LEAVE: {
		}
		break;
		case MeetingSession.VIDEO_NOTIFY_CAMERA_DID_OPEN: {
//			showShortToast("获取摄像头对象成功");
			mCamera = (Camera) args[0];
			reSetRotation();
			usefront = (Boolean) args[1];

			if (null == mCamera) {
				// showToast("没有打开摄像头权限,请添加权限！");
				new AlertDialog.Builder(this).setTitle("提示").setMessage("打开相机失败,请检查软件是否具有拍照权限？有,请重启手机;没有,请开通权限").setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						exit();
					}
				}).show();

				return;
			} else {
//				showShortToast(mCamera.getParameters().getPictureSize().width + "-----" + mCamera.getParameters().getPictureSize().height);
				//	                    List<Camera.Size> sizes = mCamera.getParameters().getSupportedPreviewSizes();
				//	                    Camera.Size tempSize = null;
				//	                    for (Camera.Size size:sizes){
				//	                        if(tempSize ==null){
				//	                            tempSize = size;
				//	                        }
				//	                        if(size.width>tempSize.width){
				//	                            tempSize = size;
				//	                        }
				//	                    }
				//	                    mCamera.getParameters().setPreviewSize(tempSize.width,tempSize.height);
			}
		}
		break;
		case MeetingSession.VIDEO_NOTIFY_CAMERA_WILL_CLOSE: {
			mCamera = null;

		}
		break;

		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.msgControlBtn:
			ObjectAnimator translationAnimator = null;
			ObjectAnimator alphaAnimator = null;
			if (isOpenMsgLayout) {
				translationAnimator = ObjectAnimator.ofFloat(rightLayout, "translationX", 0f, msgLayout.getMeasuredWidth());
				alphaAnimator = ObjectAnimator.ofFloat(msgLayout, "alpha", 1f, 0.5f);
				isOpenMsgLayout = false;
				msgControlBtn.setBackgroundResource(R.drawable.btn_open);
			} else {
				translationAnimator = ObjectAnimator.ofFloat(rightLayout, "translationX", msgLayout.getMeasuredWidth(), 0f);
				alphaAnimator = ObjectAnimator.ofFloat(msgLayout, "alpha", 0.5f, 1f);
				isOpenMsgLayout = true;
				msgControlBtn.setBackgroundResource(R.drawable.btn_close);
			}

			translationAnimator.setDuration(500);
			alphaAnimator.setDuration(500);
			alphaAnimator.start();
			translationAnimator.start();
			break;

		case R.id.sendMsg:
			List<ImageVO> imageVOs = DataSupport.findAll(ImageVO.class);
			//			showShortToast(Arrays.toString(imageVOs.toArray()));
			EditText msgEdit = (EditText) findViewById(R.id.msgEdit);
			if (TextUtils.isEmpty(msgEdit.getText())) {
				showShortToast("请输入消息");
				return;
			}

			JSONObject params = new JSONObject();
			try {
				params.put("senderID", myPid);
				params.put("toID", 0);
				params.put("name", userName);

			} catch (JSONException e) {
				showShortToast("发送消息 错误");
				e.printStackTrace();
			}
			MeetingSession.getInstance().sendTextMessage(0,msgEdit.getText().toString() , params);

			MettingMessageVO mettingMessageVO = new MettingMessageVO();
			mettingMessageVO.setType(MettingMessageVO.TYPE.SELF);
			mettingMessageVO.setMessage(msgEdit.getText().toString().trim());
			mettingMessageVO.setUserName(userName);
			messageList.add(mettingMessageVO);
			//			setMsgAdapter();
			msgRecyclerView.getAdapter().notifyDataSetChanged();
			msgEdit.getText().clear();
			msgRecyclerView.smoothScrollToPosition(msgRecyclerView.getAdapter().getItemCount());


			break;

		case R.id.photoGraph:
			//			if (mCamera == null) {
			//				showShortToast("摄像头未打开，不能拍照");
			//				return;
			//			}
			//			orientaitonListener.rememberOrientation();
			//			Camera.Parameters parameters = mCamera.getParameters();
			//			List<Camera.Size> sizes = parameters.getSupportedPictureSizes();
			//			Camera.Size tempSize = null;
			//			for (Camera.Size s : sizes) {
			//				if (tempSize == null) {
			//					tempSize = s;
			//				}
			//				if (s.width < tempSize.width) {
			//					tempSize = s;
			//				}
			//			}
			//			parameters.setPictureSize(tempSize.width, tempSize.height);
			//			int rotation = (mDisplayOrientation
			//					+ orientaitonListener.getRememberedNormalOrientation() + mLayoutOrientation) % 360;
			//			parameters.setRotation(rotation);
			//			parameters.set("rotation", rotation);
			//			mCamera.setParameters(parameters);
			//			mCamera.takePicture(new Camera.ShutterCallback() {
			//				@Override
			//				public void onShutter() {
			//					ToneGenerator tone = new ToneGenerator(
			//							AudioManager.STREAM_DTMF, ToneGenerator.MIN_VOLUME);
			//					tone.startTone(ToneGenerator.TONE_PROP_BEEP);
			//				}
			//			},null, new Camera.PictureCallback() {
			//				@Override
			//				public void onPictureTaken(byte[] data, Camera camera) {
			//					if (camera == mCamera) {
			//						try {
			//							Camera.Parameters p = mCamera.getParameters();
			//							p.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
			//							LogUtil.w("video", "Focus Mode = " + p.getFocusMode());
			//							mCamera.setParameters(p);
			//						} catch (Exception e) {
			//							LogUtil.w("video", "Error focus mode: " + e.getMessage());
			//						}
			//					}
			//					camera.startPreview();
			//					new SavePicTask(data).execute();
			//
			//				}
			//			});
			photoGraph();
			break;

		case R.id.photoPreview:
			Intent intent=new Intent(VideoActivity.this, PhotoPreviewActivity.class);
			intent.putExtra("rptNo", returnSubVideoSrvyVO.getTaskNo());
			startActivity(intent);
			break;
			
		case R.id.returnBack:
			exitMeeting(1, "确定退出视频");
			break;

		default:
			break;
		}
	}

	private void photoGraph(){
		if (mCamera == null) {
//			showShortToast("摄像头未打开，不能拍照");
			return;
		}
		orientaitonListener.rememberOrientation();
		Camera.Parameters parameters = mCamera.getParameters();
		List<Camera.Size> sizes = parameters.getSupportedPictureSizes();
		Camera.Size tempSize = null;
		for (Camera.Size s : sizes) {
			if (tempSize == null) {
				tempSize = s;
			}
			if (s.width < tempSize.width) {
				tempSize = s;
			}
		}
		parameters.setPictureSize(tempSize.width, tempSize.height);
		int rotation = (mDisplayOrientation
				+ orientaitonListener.getRememberedNormalOrientation() + mLayoutOrientation) % 360;
		parameters.setRotation(rotation);
		parameters.set("rotation", rotation);
		mCamera.setParameters(parameters);
		mCamera.takePicture(new Camera.ShutterCallback() {
			@Override
			public void onShutter() {
				ToneGenerator tone = new ToneGenerator(
						AudioManager.STREAM_DTMF, ToneGenerator.MIN_VOLUME);
				tone.startTone(ToneGenerator.TONE_PROP_BEEP);
			}
		},null, new Camera.PictureCallback() {
			@Override
			public void onPictureTaken(byte[] data, Camera camera) {
				if (camera == mCamera) {
					try {
						Camera.Parameters p = mCamera.getParameters();
						p.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
						LogUtil.w("video", "Focus Mode = " + p.getFocusMode());
						mCamera.setParameters(p);
					} catch (Exception e) {
						LogUtil.w("video", "Error focus mode: " + e.getMessage());
					}
				}
				camera.startPreview();
				new SavePicTask(data).execute();

				showShortToast("拍照成功");
				
				JSONObject params = new JSONObject();
				try {
					params.put("senderID", myPid);
					params.put("toID", 0);
					params.put("name", userName);

				} catch (JSONException e) {
					showShortToast("发送消息 错误");
					e.printStackTrace();
				}
				MeetingSession.getInstance().sendTextMessage(0,"我上传了一张照片!" , params);

				MettingMessageVO mettingMessageVO = new MettingMessageVO();
				mettingMessageVO.setType(MettingMessageVO.TYPE.SELF);
				mettingMessageVO.setMessage("我上传了一张照片!");
				mettingMessageVO.setUserName(userName);
				messageList.add(mettingMessageVO);
				//			setMsgAdapter();
				msgRecyclerView.getAdapter().notifyDataSetChanged();
				msgRecyclerView.smoothScrollToPosition(msgRecyclerView.getAdapter().getItemCount());
				
			}
		});
	}

	class SavePicTask extends AsyncTask<Void,Void,Void>{
		private byte[] picData;
		public SavePicTask(byte[] picData){
			this.picData = picData;
		}
		@Override
		protected Void doInBackground(Void... params) {
			String imagePath = FileUtil.getImageDirectory("IMG"+TimeUtils.getDetailDate()+".jpg");
			FileOutputStream fos = null;
			try {
				fos = new FileOutputStream(imagePath);
				fos.write(picData,0,picData.length);
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				if(fos!=null){
					try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			File file = null;
			if((file = new File(imagePath)).exists()){
				ImageVO imageVO = new ImageVO();
				imageVO.setPicPath(imagePath);
				imageVO.setRptNo(returnSubVideoSrvyVO.getTaskNo());
				imageVO.setCarNo(returnSubVideoSrvyVO.getCarNo());
				imageVO.setCompCde("");
				imageVO.setDptCde("32000002");
				imageVO.setPicName(file.getName());
				imageVO.setPicPath(imagePath);
				imageVO.setPicDescription("");
				imageVO.setLongitude("");
				imageVO.setLatitude("");
				imageVO.setCreateTm(TimeUtils.getDate());
				imageVO.setClaimTaskId(returnSubVideoSrvyVO.getClaimTaskId());
				imageVO.setClaimTaskType(returnSubVideoSrvyVO.getClaimTaskType());
				imageVO.setLossEmpCde(returnSubVideoSrvyVO.getSetLossCde());
				imageVO.setLossEmpNme(returnSubVideoSrvyVO.getSetLossNme());
				imageVO.save();
				startService(new Intent(VideoActivity.this, ImageService.class));
			}
			return null;
		}
	}

	Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) 
		{
			switch (msg.what) {
			case -1:
				showShortToast((String) msg.obj);
				break;

			case 0:
				ResponseCapture responseCapture=new ResponseCapture();
				responseCapture=(ResponseCapture) msg.obj;
				if(responseCapture.getResult().getCode().equals("1")){
					List<CaptureInfo> list=responseCapture.getList();
					if(list!=null&&list.size()>0){
						String cntt=list.get(0).getCntt();
						String[] str = cntt.split("_");
						if (str[0].equals("takePhoto")) {
							photoGraph();
							msgId=list.get(0).getMsgId();
						}
					}
				}else if(responseCapture.getResult().getCode().equals("2")){
					ExitUtils.Unlogin(VideoActivity.this, responseCapture.getResult().getMessage());
				}
				break;

			default:
				break;
			}
		};
	};
	Runnable runnable=new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			testCapture();
			handler.postDelayed(runnable, 3000);
		}
	};



	//抓拍请求
	private void testCapture(){

		RequestHead requestHead=new RequestHead("android", "getMsgList", "msg");
		RequestData requestData=new RequestData(returnSubVideoSrvyVO.getTaskNo(), "1", 
				returnSubVideoSrvyVO.getSetLossNme(), returnSubVideoSrvyVO.getSetLossCde(), "1",
				returnSubVideoSrvyVO.getClaimTaskType(), returnSubVideoSrvyVO.getClaimTaskId(), msgId);
		RequestCapture requestCapture=new RequestCapture(requestHead, requestData);
		new CaptureThread(VideoActivity.this, handler, requestCapture).start();
	}
	
	private void sendMsg(){
		JSONObject params = new JSONObject();
		try {
			params.put("senderID", myPid);
			params.put("toID", 0);
			params.put("name", userName);

		} catch (JSONException e) {
			showShortToast("发送消息 错误");
			e.printStackTrace();
		}
		MeetingSession.getInstance().sendTextMessage(0,"定损员，您好!\n我在"+address , params);

		MettingMessageVO mettingMessageVO = new MettingMessageVO();
		mettingMessageVO.setType(MettingMessageVO.TYPE.SELF);
		mettingMessageVO.setMessage("定损员，您好!\n我在"+address);
		mettingMessageVO.setUserName(userName);
		messageList.add(mettingMessageVO);
		//			setMsgAdapter();
		msgRecyclerView.getAdapter().notifyDataSetChanged();
		msgRecyclerView.smoothScrollToPosition(msgRecyclerView.getAdapter().getItemCount());
		
	}

	public void exit() {
		stopRecording();
		NotificationCenter.getInstance().removeAllObservers();
		MeetingSession.getInstance().exitMeeting();
		orientaitonListener.disable();
		orientaitonListener = null;
		finish();
	}

	@Override
	public void onBackPressed() {
		exitMeeting(1, "确定退出视频");

	}

	/**
	 * 退出
	 */
	public void exitMeeting(int type, String dialogMessage) {
		if (type == 0) {
			exit();
			return;
		}
		new AlertDialog.Builder(this).setTitle("提示").setMessage(dialogMessage).setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				exit();
			}
		}).setNegativeButton("取消", null).show();

	}


	/**
	 * 设置视频方向
	 */
	public void reSetRotation() {
		WindowManager wm = this.getWindowManager();
		int rotation = wm.getDefaultDisplay().getRotation();
		int degrees = 0;

		switch (rotation) {
		case Surface.ROTATION_0:
			degrees = 0;
			MeetingSession.getInstance().setRotate(1);
			break;
		case Surface.ROTATION_90:
			degrees = 90;
			MeetingSession.getInstance().setRotate(4);
			break;
		case Surface.ROTATION_180:
			degrees = 180;
			MeetingSession.getInstance().setRotate(2);
			break;
		case Surface.ROTATION_270:
			degrees = 270;
			MeetingSession.getInstance().setRotate(3);
			break;
		}
		Log.d("ROT", "" + rotation + "--");
		int displayOrientation;
		CameraInfo cameraInfo = new CameraInfo();
		Camera.getCameraInfo(0, cameraInfo);
		// Camera direction
		if (cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT) {
			displayOrientation = (cameraInfo.orientation + degrees) % 360;
			displayOrientation = (360 - displayOrientation) % 360;
		} else {
			displayOrientation = (cameraInfo.orientation - degrees + 360) % 360;
		}

		mDisplayOrientation =displayOrientation;
		//        mDisplayOrientation = (cameraInfo.orientation - degrees + 360) % 360;
		mLayoutOrientation = degrees;
		try {
			if (mCamera != null)
				mCamera.setDisplayOrientation(displayOrientation);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 闪光灯
	 *
	 * @param value
	 */
	public void openLamp(String value) {
		try {
			Camera.Parameters par = mCamera.getParameters();
			par.setFlashMode(value);// 开启闪光灯
			mCamera.setParameters(par);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 调节焦距
	 *
	 * @param type
	 */
	public void zoom(int type) {

		try {
			Camera.Parameters params = mCamera.getParameters();
			final int MAX = params.getMaxZoom();
			Log.e("===", MAX + "<<<<<<<");
			if (MAX == 0)
				return;

			int zoomValue = params.getZoom();
			// 1拉开
			if (type == 1) {
				zoomValue += 2;
			} else {
				zoomValue -= 2;
			}
			if (zoomValue > MAX)
				zoomValue = MAX;

			if (zoomValue < 0)
				zoomValue = 0;
			params.setZoom(zoomValue);
			mCamera.setParameters(params);

		} catch (Exception e) {
		}
	}



	/**
	 * 播放自己的视频
	 */
	protected void playVideo() {
		// 后置摄像头false
		MeetingSession.getInstance().switchCamera(false);
		MeetingSession.getInstance().PlayVideo(0, true, surfaceView, 0, 0, 1,
				1, 0, false, 0);
		MeetingSession.getInstance().setWatchMeWish(true);

	}

	/**
	 * 开始录制视频
	 */
	protected void startRecording() {
		// 开始录制：
		MeetingSession.getInstance().setFocusUser(myPid);// 将某人选为焦点，录制时将录制该人的视频
		MeetingSession.getInstance().serverRecording(true);// 开始服务器录制
	}

	/**
	 * 结束录制视频
	 */
	protected void stopRecording() {
		MeetingSession.getInstance().serverRecording(false);// 停止服务器录制
	}
}